#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

void* send_msg(void* arg)
{
    int clientfd = *(int *)arg;
    char msg[128];
    while(1)
    {
        if(fgets(msg, sizeof(msg), stdin) == NULL)
        {
            perror("fgets");
            break;
        }
        int ret_val = send(clientfd, msg, strlen(msg), 0);
        if(ret_val < 0)
        {
            perror("send");
            break;
        }
        std::cout << "发送信息" << ret_val << "字节" << std::endl;
    }
    return NULL;
}

void* recv_msg(void* arg)
{
    int clientfd = *(int *)arg;
    char msg[128];
    int ret_val = -1;
    while(1)
    {
        bzero(msg, sizeof(msg));
        ret_val = recv(clientfd, msg, sizeof(msg), 0);
        if(ret_val == 0)
        {
            std::cout << "客户端断开连接" << std::endl;
            break;
        }
        else if(ret_val < 0)
        {
            perror("recv");
            break;
        }
        else
        {
            std::cout << "接收到数据：" << msg << std::endl;
        }
    }
    close(clientfd);
    return NULL;
}

int main(int argc, char const *argv[])
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd == -1)
    {
        perror("socket");
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8848);

    int ret_val = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret_val == -1)
    {
        perror("bind");
        close(sockfd);
        return -1;
    }

    ret_val = listen(sockfd, 10);
    if(ret_val == -1)
    {
        perror("listen");
        close(sockfd);
        return -1;
    }

    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    while(1)
    {
        int clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &client_addr_len);
        if(clientfd == -1)
        {
            perror("accept");
            continue;
        }
        std::cout << "新用户连接" << std::endl;
        pthread_t send_tid, recv_tid;
        pthread_create(&send_tid, NULL, send_msg, (void*)&clientfd);
        pthread_create(&recv_tid, NULL, recv_msg, (void*)&clientfd);
        pthread_detach(send_tid);
        pthread_detach(recv_tid);
    }

    close(sockfd);
    return 0;
}